package algorithm.doublePointer;

import java.util.Arrays;

// 复写零
public class LC1089 {
    public void duplicateZeros(int[] arr) {
        int len = arr.length;

        // 计算复写后最后一个元素在原数组中的位置
        int cur = -1, dest = -1;
        while (dest < len - 1) {
            cur++;
            if (arr[cur] != 0) {
                dest++;
            } else {
                dest += 2;
            }
        }

        // 处理边界情况
        if (dest == len) {
            arr[len - 1] = 0;
            cur--; dest -= 2;
        }

        // 从后往前复写
        while (cur >= 0) {
            if (arr[cur] != 0) {
                arr[dest--] = arr[cur--];
            } else {
                arr[dest--] = 0;
                arr[dest--] = 0;
                cur--;
            }
        }
    }

    public static void main(String[] args) {
        LC1089 lc1089 = new LC1089();

        int[] arr = {1, 0, 2, 3, 0, 4};
        lc1089.duplicateZeros(arr);
        System.out.println(Arrays.toString(arr));
    }
}
